/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import logging.CommonsLogging;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import vo.rb_ot_str;

/**
 *
 * @author Shuhail
 */
public class rb_emp_ot_persist {
 
    Logger logger = CommonsLogging.getInstance().getLogger();
    Session sess = null;
    Transaction tx = null;
    
    public static rb_emp_ot_persist getInstance() {
        
        return new rb_emp_ot_persist();
    }
    public rb_emp_ot_persist() {
        
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        sess = sf.openSession();
        tx = sess.beginTransaction();
        tx.begin();
    }
    
    public List<rb_ot_str> getAllOTAndType() {
        
        Query query = sess.getNamedQuery("getAllEmployeeOT");
        List list = query.list();
        return list;
    }
    
    public List<String> getDistictEmployeeTypes() {
        
        Query query = sess.getNamedQuery("getDistinctEmployeeTypes");
        List<String> list = new ArrayList<String>();
        List l = query.list();
        Iterator it = l.iterator();
        while(it.hasNext()) {
            
            list.add(((String)it.next()));
        }
        return list;
    }
    public void insert(rb_ot_str ot) {
        if(logger.isDebugEnabled()) {
            logger.info("****In rb otr persists to insert/update***");
        }
        rb_ot_str str = (rb_ot_str) sess.get(rb_ot_str.class, ot.getEmployee_type());
        if(str==null) {
            if(logger.isDebugEnabled()){
                logger.info("New Record .. So inserting");
            }
            sess.save(ot);
            tx.commit();
        }
        else {
            if(logger.isDebugEnabled()) {
                logger.info("Already Exists .  So updating the record");
            }
            str.setOt_amt_per_hr(ot.getOt_amt_per_hr());
            sess.update(str);
            tx.commit();
        }
        
    }
    
    public static void main(String[] args) {
        rb_ot_str r = new rb_ot_str();
        r.setEmployee_type("Sales");
        r.setOt_amt_per_hr(113);
        new rb_emp_ot_persist().insert(r);
        System.out.println(new rb_emp_ot_persist().getDistictEmployeeTypes());
    }
}
